package com.example.micro.netty.server.thread;

import java.util.concurrent.Semaphore;

/**
 * Semaphore实现交替打印
 */
//todo 暂时不对
public class AlternateSemaphorePrint {

    private static Semaphore semaphoreOdd = new Semaphore(1);
    private static Semaphore semaphoreEven = new Semaphore(1);
    private static int index = 0;

    public static void main(String[] args) {
        new Thread(() -> {
            try {
                while (true) {
                    System.out.println(Thread.currentThread().getName()
                            + ":" + index++);
                    semaphoreOdd.release();
                    semaphoreEven.acquire();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(500);
                while (true) {
                    System.out.println(Thread.currentThread().getName()
                            + ":" + index++);
                    semaphoreEven.release();
                    semaphoreOdd.acquire();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();
    }

}
